<?php
namespace Admin\Controller;
use Think\Exception;

/**
 * 权限管理相关控制器
 * Class AuthController
 * @package Admin\Controller
 */
class AuthController extends AbstractController {

    /**
     * 权限列表
     */
    public function index(){
        $this->auth_url_model = D("Authrule");
        //$AuthRules = $this->auth_url_model->select();
        $result = $this->auth_url_model->select();
        $tree = new \Think\Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        $AuthRules=array();
        foreach ($result as $A){
            $AuthRules[$A['ID']]=$A;

        }

        foreach ($result as $n=> $r) {
            $result[$n]['Key'] = $n;
            $result[$n]['ParentID_node'] = ($r['ParentID']) ? ' class="child-of-node-' . $r['ParentID'] . '"' : '';
            $result[$n]['style'] = empty($r['ParentID']) ? '' : 'display:none;';
            $result[$n]['str_manage'] = '';
            if(true){
                $result[$n]['str_manage'] .= '<a href="' . U("Auth/add", array("ParentID" => $r['ID'], "arid" => I("get.arid"))) . '">添加子权限</a>';
            }
            if(true){
                if(strlen($result[$n]['str_manage']) > 0){
                    $result[$n]['str_manage'] .= ' | ';
                }
                $result[$n]['str_manage'] .= '<a href="' . U("Auth/edit", array("id" => $r['ID'],"arid" => I("get.arid"))) . '">编辑</a>';
            }
            if(true){
                if(strlen($result[$n]['str_manage']) > 0){
                    $result[$n]['str_manage'] .= ' | ';
                }
                $result[$n]['str_manage'] .=  '<a class="js-ajax-delete" href="' . U("Auth/delete", array("id" => $r['ID'], "arid" => I("get.arid")) ). '">删除</a>';
            }
            //$result[$n]['str_manage'] = '<a href="' . U("Auth/add", array("ParentID" => $r['ID'], "arid" => I("get.arid"))) . '">添加子权限</a> | <a href="' . U("Auth/edit", array("id" => $r['ID'],"arid" => I("get.arid"))) . '">编辑</a> | <a class="js-ajax-delete" href="' . U("Auth/delete", array("id" => $r['ID'], "arid" => I("get.arid")) ). '">删除</a> ';
        }

        $tree->init($result);
        $str = "<tr id='node-\$ID' \$ParentID_node style='\$style'>
                    <td style='padding-left:20px;' class='expander'></td>
                    <td>\$Key</td>
                    <td>\$Title</td>
                    <td>\$spacer\$Name</td>
                    <td>\$str_manage</td>
                </tr>";

        $categorys = $tree->get_tree(0, $str);
        $this->assign("categorys", $categorys);
        $this->display();
    }

    /**
     * 添加权限
     */
    public function add(){
        if(IS_POST){
            $data = $_POST;
            $where['Name'] = strtolower($data['Name']);
            $Authrule = D("Authrule")->where($where)->find();

            $data['Name'] = strtolower($data['Name']);
            if (empty($Authrule)) {
                $result = D("Authrule")->add($data);
                if ($result) {
                    $this->success("添加成功！");
                } else {
                    $this->error("添加失败！");
                }
            } else {
                $this->error('失败，已经有该记录了！');
            }
        }else{
            $Parent = null;
            if(isset($_GET['ParentID'])){
                $Parent = D("Authrule")->where(array('ID'=>intval($_GET['ParentID'])))->find();
            }
            $this->assign("Parent", $Parent);
            $this->display();
        }

    }

    /**
     * 编辑权限
     */
    public function edit(){
        if (IS_POST) {
            $ID = I('post.ID','intval');
            $data = $_POST;
            $data['Name'] = strtolower($data['Name']);
            $result = D("Authrule")->where(array('ID'=>$ID))->save($data);
            if ($result) {
                $this->success("修改成功！");
            } else {
                $this->error("修改失败！");
            }
        }else{
            $ID = I('get.id','intval');
            $Authrule = D("Authrule")->where(array('ID'=>$ID))->find();

            $Authrule = D("Authrule")->where(array("ID" => $ID))->find();
            $result = D("Authrule")->order(array("ID" => "desc"))->select();
            $tree = new \Think\Tree();
            foreach ($result as $r) {
                $r['selected'] = $r['ID'] == $Authrule['ParentID'] ? 'selected' : '';
                $array[] = $r;
            }
            $str = "<option value='\$ID' \$selected>\$spacer \$Title</option>";
            $tree->init($array);
            $select_categorys = $tree->get_tree(0, $str);
            $this->assign("Authrule", $Authrule);

            $this->assign("select_categorys", $select_categorys);
            $this->display();
        }
    }

    /**
     * 删除权限
     */
    public function delete(){
        try{
            $id = I('id',0,'int');
            if($id){
                $rule = M('Authrule')->find($id);
                if($rule){
                    $count = M('Authrule')->where(array('ParentID' => $rule['ID']))->count();
                    if($count){
                        throw new Exception('当前权限还有子权限，不能直接删除');
                    }
                    $accessCount = M('Authaccess')->where(array('RuleName' => $rule['Name']))->count();
                    if($accessCount){
                        throw new Exception('当前权限已被授权，不能删除');
                    }
                    $result = M('Authrule')->delete($id);
                    if($result){
                        $this->success('删除成功');
                    }else{
                        $this->error('删除失败');
                    }
                }else{
                    throw new Exception('参数错误');
                }
            }else{
                throw new Exception('参数错误');
            }
        }catch (Exception $exception){
            $this->error($exception->getMessage());
        }
    }

    // 角色授权
    public function authorize() {
        if(IS_POST){
            $this->auth_access_model = D("Authaccess");
            $RoleID = I("post.RoleID",0,'intval');
            if(!$RoleID){
                $this->error("需要授权的角色不存在！");
            }
            if (is_array($_POST['AuthRule']) && count($_POST['AuthRule'])>0) {
                $this->auth_access_model->where(array("RoleID" => $RoleID))->delete();
                foreach ($_POST['AuthRule'] as $AuthRule) {
                    $this->auth_access_model->add(array("RoleID"=>$RoleID,"RuleName"=>$AuthRule,'Type'=>'admin_url'));
                }
                $this->success("授权成功！");
            }else{
                $this->auth_access_model->where(array("RoleID" => $RoleID))->delete();
                $this->success("没有接收到数据，执行清除授权成功！");
            }
        }else{
            $this->auth_access_model = D("Authaccess");
            $this->auth_url_model = D("Authrule");
            //角色ID
            $RoleID = I("get.id",0,'intval');
            if (empty($RoleID)) {
                $this->error("参数错误！");
            }
            $AuthruleArr = $this->auth_url_model->select();
            $AuthAccessArr = $this->auth_access_model->where(array('RoleID'=>$RoleID))->select();
            $result = array();
            foreach ($AuthruleArr as $key => $val) {
                foreach ($AuthAccessArr as $k => $v) {
                    if($val['Name']==$v['RuleName'] and $val['Type']==$v['Type']){
                        $val['Checked'] = 'true';
                    }
                }
                $result[]=$val;
            }
            $AuthRules = make_tree($result,'ID','ParentID','Son');
            $this->assign("AuthRules", json_encode($AuthRules));
            $this->assign("RoleID", $RoleID);
            $this->assign('Role',M('Role')->find($RoleID));
            $this->display();
        }
    }
}